//
//  SQPopOverView.m
//  sq580.com.followup
//
//  Created by Faith on 16/4/20.
//  Copyright © 2016年 hjw. All rights reserved.
//

#import "PopOverView.h"
#import "Global.h"

static NSMutableDictionary* SQPopOverViewTargetCollection;

typedef enum{
    PopUP = 0,
    PopDown
}popType;

@interface PopOverView ()
@property (strong, nonatomic) NSMutableArray *btnArrM;
@property (strong, nonatomic) POPSpringAnimation *springAnimation;
@property (strong, nonatomic) UIView *btnView;
@end

@implementation PopOverView

- (instancetype)init{
    if (self = [super init]) {
        [self addBtn];
    }
    return self;
}
- (void)addBtn {
    NSString *path = [[NSBundle mainBundle] pathForResource:@"pop.plist" ofType:nil];
    NSArray *arr = [NSArray arrayWithContentsOfFile:path];
    self.btnArrM = [NSMutableArray array];
    CGFloat itemW = 80;
    CGFloat itemH = 30;
    CGFloat itemMargin = ([UIScreen mainScreen].bounds.size.width - 3 *itemW) / 4;
    //    self.btnView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 300)];
    //    self.btnView.center = CGPointMake([UIScreen mainScreen].bounds.size.width/2, [UIScreen mainScreen].bounds.size.height/2);
    //    self.btnView.backgroundColor = [UIColor whiteColor];
    //    [self addSubview:self.btnView];
    __weak typeof(self) weakSelf = self;
    [arr enumerateObjectsUsingBlock:^(NSDictionary *dict, NSUInteger i, BOOL * _Nonnull stop) {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        
        NSAttributedString *attributedStr = [[NSAttributedString alloc]initWithString:dict[@"title"] attributes:@{NSForegroundColorAttributeName:[UIColor whiteColor],NSFontAttributeName:[UIFont systemFontOfSize:12]}];
        [btn setAttributedTitle:attributedStr forState:UIControlStateNormal];
        int R = (arc4random() % 256) ;
        int G = (arc4random() % 256) ;
        int B = (arc4random() % 256) ;
        [btn setBackgroundColor:[UIColor colorWithRed:R/255.0 green:G/255.0 blue:B/255.0 alpha:1.0]];
        //        [btn setImage:[UIImage imageNamed:dict[@"icon"]] forState:UIControlStateNormal];
        NSInteger row = i/3;
        NSInteger col = i%3;
        btn.frame = CGRectMake(itemMargin + col * (itemW + itemMargin),   itemMargin + 200 + row * (itemH + itemMargin), itemW, itemH);
        btn.tag = i+1;
        [btn addTarget:weakSelf action:@selector(popBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
        [weakSelf addSubview:btn];
        [weakSelf.btnArrM addObject:btn];
        btn.layer.cornerRadius = 10;
        btn.clipsToBounds = YES;
    }];
}

- (void)popBtnClicked:(UIButton *)sender {
    CGFloat itemW = 100;
    CGFloat itemH = 30;
        CGFloat itemMargin = ([UIScreen mainScreen].bounds.size.width - 3 *itemW) / 4;
    CGPoint centerPoint = CGPointMake([UIScreen mainScreen].bounds.size.width/2, 2*itemMargin + 200 + itemH);
    if (sender.tag == 6) {
        __weak typeof(self) ws = self;
        [UIView animateWithDuration:0.6 animations:^{
            for (UIButton *btn in ws.btnArrM) {
                btn.center = centerPoint;
            }
        } completion:^(BOOL finished) {
            for (UIButton *btn in ws.btnArrM) {
                [btn removeFromSuperview];
            }
            [ws.btnArrM removeAllObjects];
            for (int i = 0; i < 2; i++) {
                UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
                NSAttributedString *attributedStr = [[NSAttributedString alloc]initWithString:[NSString stringWithFormat:@"用户自动定义%d",i+1] attributes:@{NSForegroundColorAttributeName:[UIColor whiteColor],NSFontAttributeName:[UIFont systemFontOfSize:12]}];
                [btn setAttributedTitle:attributedStr forState:UIControlStateNormal];
                int R = (arc4random() % 256) ;
                int G = (arc4random() % 256) ;
                int B = (arc4random() % 256) ;
                [btn setBackgroundColor:[UIColor colorWithRed:R/255.0 green:G/255.0 blue:B/255.0 alpha:1.0]];
                //        [btn setImage:[UIImage imageNamed:dict[@"icon"]] forState:UIControlStateNormal];
                btn.frame = CGRectMake(0, 0, itemW, itemH);
                btn.center = centerPoint;
                btn.tag = 7+i;
                [btn addTarget:ws action:@selector(popBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
                [ws addSubview:btn];
                [ws.btnArrM addObject:btn];
                btn.layer.cornerRadius = 10;
                btn.clipsToBounds = YES;
            }
            
            [UIView animateWithDuration:0.6 animations:^{
                for (UIButton *btn in ws.btnArrM) {
                    if (btn.tag == 7) {
                        btn.center = CGPointMake(centerPoint.x, centerPoint.y-30);
                    }else {
                        btn.center = CGPointMake(centerPoint.x, centerPoint.y+30);
                    }
                }
            }];
            
        }];
    }
    else {
        if ([self.backgroundViewDelegate respondsToSelector:@selector(popOverView:onPopBtnClicked:)]) {
            [self.backgroundViewDelegate popOverView:self onPopBtnClicked:sender];
        }
    }
}

- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
    UIView *view = [super hitTest:point withEvent:event];
    if (view == nil) {
        for (UIButton *btn in self.btnArrM) {
            CGPoint temppoint = [btn convertPoint:point fromView:self];
            if (CGRectContainsPoint(btn.bounds, temppoint)) {
                view = btn;
            }
        }
        
    }
    return view;
}

/**
 *  显示
 */
- (void)show {
    if ([NSThread isMainThread]) {
        self.backgroundColor = [UIColor whiteColor];
        [self.layer setBorderWidth:0.5];
        [self.layer setBorderColor:[UIColor lightGrayColor].CGColor];
        
        if (self.backgroundView) {
            [self.backgroundView removeFromSuperview];
        }
        
        UIView* window = [UIApplication sharedApplication].keyWindow;
        if (!window) {
            window = [self getCurrentVC].view;
        }
        
        if (!self.backgroundView && !self.disableBackgroundView) {
            // 创建背景蒙板
            _backgroundView = [UIButton buttonWithType:UIButtonTypeCustom];
            self.backgroundView.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height);
            self.backgroundView.backgroundColor = [UIColor blackColor];
            self.backgroundView.alpha = 0.8;
            [self.backgroundView addTarget:self action:@selector(onTapBackgroundView:) forControlEvents:UIControlEventTouchUpInside];
            [window addSubview:self.backgroundView];
        }
        
        
        self.alpha = 0;
        [window addSubview:self];
        [window bringSubviewToFront:self];
        [UIView animateWithDuration:0.5 animations:^{
            self.alpha = 1;
        }];
    }
    else {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self show];
        });
    }
}


//获取当前显示的视图控制器
- (UIViewController *)getCurrentVC
{
    UIViewController* topVC = [[UIApplication sharedApplication].delegate window].rootViewController;
    while (topVC.presentedViewController) {
        topVC = topVC.presentedViewController;
    }
    return topVC;
}

/**
 *  显示
 *  @param target 唯一性标识，同一个标识不会显示多个弹出视图实例
 */
- (void)showWithTarget:(NSInteger)target {
    BOOL needShow = NO;
    NSNumber* key =[NSNumber numberWithInteger:target];
    if (!SQPopOverViewTargetCollection) {
        SQPopOverViewTargetCollection = [NSMutableDictionary dictionary];
        [SQPopOverViewTargetCollection setObject:self forKey:key];
        needShow = YES;
    }
    else {
        if (![SQPopOverViewTargetCollection objectForKey:key]) {
            [SQPopOverViewTargetCollection setObject:self forKey:key];
            needShow = YES;
        }
    }
    if (needShow) {
        _target = target;
        [self show];
    }
}

/**
 *  关闭
 */
- (void)hide {
    if ([NSThread isMainThread]) {
        NSNumber* key =[NSNumber numberWithInteger:_target];
        if (SQPopOverViewTargetCollection && [SQPopOverViewTargetCollection objectForKey:key]) {
            [SQPopOverViewTargetCollection removeObjectForKey:key];
        }
        __weak typeof(self) ws = self;
        [UIView animateWithDuration:0.5 animations:^{
            self.alpha = 0;
            self.backgroundView.alpha = 0;
        } completion:^(BOOL finished) {
            [self.backgroundView removeFromSuperview];
            [self removeFromSuperview];
        }];
    }
    else {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self hide];
        });
    }
}

/**
 关闭
 
 @param animated 是否启用动画
 */
- (void)hide:(BOOL)animated {
    if (animated) {
        if ([NSThread isMainThread]) {
            NSNumber* key =[NSNumber numberWithInteger:_target];
            if (SQPopOverViewTargetCollection && [SQPopOverViewTargetCollection objectForKey:key]) {
                [SQPopOverViewTargetCollection removeObjectForKey:key];
            }
            
            [UIView animateWithDuration:0.5 animations:^{
                self.alpha = 0;
                self.backgroundView.alpha = 0;
            } completion:^(BOOL finished) {
                [self.backgroundView removeFromSuperview];
                [self removeFromSuperview];
            }];
        }
        else {
            dispatch_async(dispatch_get_main_queue(), ^{
                [self hide];
            });
        }
    }
    else {
        if ([NSThread isMainThread]) {
            NSNumber* key =[NSNumber numberWithInteger:_target];
            if (SQPopOverViewTargetCollection && [SQPopOverViewTargetCollection objectForKey:key]) {
                [SQPopOverViewTargetCollection removeObjectForKey:key];
            }
            
            [self.backgroundView removeFromSuperview];
            [self removeFromSuperview];
        }
        else {
            dispatch_async(dispatch_get_main_queue(), ^{
                [self hide];
            });
        }
    }
}

/**
 *  点击背景视图事件
 *
 *  @param sender 事件发出者
 */
- (void)onTapBackgroundView:(id)sender {
    //    if (self.backgroundViewDelegate && [self.backgroundViewDelegate respondsToSelector:@selector(popOverView:onTapBackgroundView:)]) {
    //        [self.backgroundViewDelegate popOverView:self onTapBackgroundView:sender];
    //    }
    [self hide:true];
}



@end
